package com.arvato.admin01.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class DistributedLockV1 {

    private Logger logger = LoggerFactory.getLogger(DistributedLockV1.class);
    @Resource
    private RedisTemplate redisTemplate;

    public String lockV2(String businessKey) {
        boolean result = false;
        String uniqueValue = UUID.randomUUID().toString();
        try {
            result = redisTemplate.opsForValue().setIfAbsent(businessKey, uniqueValue);
            if (!result) {
                return null;
            }
            redisTemplate.expire(businessKey, 100, TimeUnit.SECONDS);
            return uniqueValue;
        } catch (Exception ex) {
            logger.error("获取锁失败", ex);
        }
        return null;
    }

    public boolean unlockV2(String businessKey, String businessValue) {
        try {
            Object value = redisTemplate.opsForValue().get(businessKey);
            if (value == null) {
                return false;
            }
            //当前key在redis中value和当前线程手里持有的是否一致
            if (!businessValue.equals(value)) {
                //不一致，证明被其他线程获取了
                logger.info("key={}释放锁失败吗，该锁已被其他线程获取",businessKey);
                return false;
            }
            redisTemplate.delete(businessKey);
            logger.info("key={}释放锁成功",businessKey);
        } catch (Exception ex) {
            logger.error("释放锁失败", ex);
        }
        return true;
    }
}
